<?php

namespace lico\Runtime;

use lico\MVC\View;

class Response
{

    protected $dataType="";
    protected $code = "200"; //状态码
    protected $data;
    protected $contentTypeMap = [
        'text'=>'text/plain',
        'html'=>'text/html',
        'json'=>'application/json',
        'pdf'=>'application/pdf',
        'jpeg'=>'image/jpeg',
        'js'=>'text/javascript',
        'css'=>'text/css',
        'xml'=>'text/xml',
    ];
    protected $smarty;

    protected $_view;

    public function __construct(View $view)
    {
        $this->_view = $view;
    }

    public function run()
    {

        $this->output();
        return true;
    }

    /**
     * 输出
     */
    protected function output()
    {   
        $data = trim(ob_get_clean());
        if (empty($data)) {
            $data = $this->getData();
        }
        $this->setContentType($this->dataType);
        http_response_code($this->code);
        if (is_array($data) || is_object($data)) {
            print_r($data);
        } else {
            echo $data;
        }
        if (function_exists('fastcgi_finish_request')) {
            // 提高页面响应
            fastcgi_finish_request();
        }
    }

    /**
     * 设置数据
     */
    public function setData($key, $data = null)
    {
        if (is_null($data)) {
            $this->data = $key;
        } else {
            $this->data[$key] = $data;
        }
    }

    /**
     * 返回数据
     */
    public function getData($key = "")
    {
        if (!$key) {
            $data = $this->data;
        } else {
            $data = $this->data[$key];
        }
        return $data;
    }
    
    /**
     * 设置返回体内容类型
     */
    public function setContentType($type = "json")
    {
        if ($type) {
            header('Content-type:'.$this->contentTypeMap[$type].';charset=utf-8');
        }
    }

    /**
     * 设置http 状态码code
     */
    public function setCode($code)
    {
        $this->code = $code;
    }
    
    /**
     * 设置内容类型
     */
    public function setDataType($type = "json")
    {
        $this->dataType = $type;
        return $this->dataType;
    }

    /**
     * 页面404
     */
    public function page404()
    {
        header('HTTP/1.1 404 Not Found');
    }

    /**
     * smarty渲染
     */
    public function view($html)
    {
        $data = $this->getData();
        $this->_view->setData($data);
        $this->_view->smartyView($html);
    }

    /**
     * 报错错误
     */
    public function error($msg, $code = 500)
    {
        $this->setDataType('html');
        $this->setCode($code);
        $this->_view->smartyError($msg);
        $this->output();
    }
}
